package com.hzj.recipe.service.impl;

//import com.alibaba.fastjson.JSON;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.api.R;
import com.hzj.recipe.entity.Admin;
import com.hzj.recipe.rep.LoginParam;
import com.hzj.recipe.entity.User;
import com.hzj.recipe.service.AdminService;
import com.hzj.recipe.service.LoginService;
import com.hzj.recipe.service.UserService;
import com.hzj.recipe.utils.JWTUtils;
import com.hzj.recipe.utils.SnowFlake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserService userService;

    @Autowired
    private AdminService adminService;

    //雪花算法
    @Autowired
    private SnowFlake snowFlake;


    //登录
    @Override
    public R login(LoginParam loginParam) {
        String userId = loginParam.getUserNum();
        String userpassword = loginParam.getUserPassword();
        //isBlank()用来检查参数是否为空，全部空白字符也为空
        if (StringUtils.isBlank(userId) || StringUtils.isBlank(userpassword)) {
            return R.failed("账号或者密码为空");
        }
        //根据用户id和密码查询是否存在
        User user = this.userService.findUser(userId, userpassword);
        //不存在登录失败
        if (user == null) {
            return R.failed("用户名不存在或密码错误");
        }
        // 存在则使用jwt生成token
        String token = JWTUtils.createToken(user.getUserId());
        //将token放入redis中，redis   token:user信息，设置过期时间1填
        //redisTemplate.opsForValue().set("TOKEN_"+token, JSON.toJSONString(user1),30, TimeUnit.DAYS);
        //token返回给前端
        return R.ok(token);
    }

    //管理员登录
    @Override
    public R adminLogin(LoginParam loginParam) {
        //此处的adminLoginId为手机号或者邮箱
        String adminLoginId = loginParam.getUserNum();
        String adminLoginPassword = loginParam.getUserPassword();
        System.out.println("eeeeee:" + adminLoginId + adminLoginPassword);
        //isBlank()用来检查参数是否为空，全部空白字符也为空
        if (StringUtils.isBlank(adminLoginId) || StringUtils.isBlank(adminLoginPassword)) {
            return R.failed("账号或者密码为空");
        }
        //根据用户id和密码查询是否存在
        Admin admin = this.adminService.findAdmin(adminLoginId, adminLoginPassword);
        //不存在登录失败
        if (admin == null) {
            return R.failed("管理员账号不存在或密码错误");
        }
        // 存在则使用jwt生成token
        String token = JWTUtils.createToken(admin.getAdminId());
        return R.ok(token);
    }

    //注册
    @Override
    public R register(User user) {
        //账户是否存在
        if (user.getUserPhone() == null && user.getUserEmail() == null) {
            return R.failed("账号不能为空");
        }
        if (user.getUserPassword() == null) {
            return R.failed("密码不能为空");
        }

        //查找账号是否存在
        if (user.getUserPhone() != null) {
            //User user1 = userService.findPE(user.getUserPhone());
            if (userService.findPE(user.getUserPhone()) != null) {
                return R.failed("手机号已被注册");
            }
        }
        //User user2 = userService.findPE(user.getUserEmail());
        if (userService.findPE(user.getUserEmail()) != null) {
            return R.failed("邮箱已被注册");
        }

        //账户不存在，注册用户
        try {
            // 雪花算法生成id
            long id = snowFlake.nextId();
            user.setUserId(id);

            userService.save(user);
        } catch (Exception e) {
            return R.failed("注册失败");
        }
        return R.ok("注册成功");
    }

    //管理员注册
    @Override
    public R adminRegister(Admin admin) {
        //账户是否存在
        if (admin.getAdminPhone() == null && admin.getAdminEmail() == null) {
            return R.failed("账号不能为空");
        }
        if (admin.getAdminPassword() == null) {
            return R.failed("密码不能为空");
        }

        //查找账号是否存在
        if (admin.getAdminPhone() != null) {
            //Admin admin1 = adminService.findPE(admin.getAdminPhone());
            if (adminService.findPE(admin.getAdminPhone()) != null) {
                return R.failed("手机号已被注册");
            }
        }
        //Admin admin2 = adminService.findPE(admin.getAdminEmail());
        if (adminService.findPE(admin.getAdminEmail()) != null) {
            return R.failed("邮箱已被注册");
        }

        //账户不存在，注册用户
        try {
            // 雪花算法生成id
            long id = snowFlake.nextId();
            admin.setAdminId(id);

            adminService.save(admin);
        } catch (Exception e) {
            return R.failed("注册失败");
        }
        return R.ok("注册成功");
    }

    //验证token
    @Override
    public User checkToken(String token) {
        //验证token是否合法
        if (token ==null||token==""){
            return null;
        }
        //解析token
        Map<String,Object> stringObjectMap = JWTUtils.checkToken(token);
        if (stringObjectMap == null){
            return null;
        }

        User user = userService.getById((Serializable) stringObjectMap.get("userId"));
        return user;
    }

    @Override
    public Admin checkAdminToken(String token) {
        //验证token是否合法
        if (token ==null||token==""){
            return null;
        }
        //解析token
        Map<String,Object> stringObjectMap = JWTUtils.checkToken(token);
        if (stringObjectMap == null){
            return null;
        }

        Admin admin = adminService.getById((Serializable) stringObjectMap.get("userId"));
        return admin;
    }
}
